<!-- organization management -->
<script setup lang="ts">
import { reactive, ref, toRefs, onMounted, watch } from 'vue';
import { ElPagination, ElMessageBox } from "element-plus"
import { Page } from '@vben/common-ui';
import dayjs from 'dayjs';
import { $t } from '#/locales/index.js'
import { trimStringParams } from '#/utils/trimStringParams'
import { getGroupOrgCertTreeApi, updateGroupOrgStatusApi, deleteOrgApi } from '#/api/system/orgMgr';
import { getCertifiedListApi } from "#/api/certificate/list"
import subOrgIcon from '#/assets/images/sub-add.png';

import { Query, EditOrgDialog, BatchUploadOrgDialog } from './modules/orgMgr'
import { Pencil, Ban, SquarePlay, Trash2 } from '@vben/icons';
import { useMessageBox } from '#/hooks/useMessageBox';

const { confirm: confirmSubmit } = useMessageBox({})
const editOrgDialogRef = ref<InstanceType<typeof EditOrgDialog> | null>(null)
const batchUploadOrgDialogRef = ref<InstanceType<typeof BatchUploadOrgDialog> | null>(null)
const defaultExpandAll = ref(false)
const tableLoading = reactive([0, 0]);
const loading = ref(false)
const total = ref(0)
const defaultQueryData = {
  name: '',
  status: null,
  certifiedId: null
}
const queryData = reactive({ ...defaultQueryData });
const tableData = ref<any>([]);
const certListData = ref<any>([])
const pageData = reactive({
  curPage: 1,
  pageSize: 10,
});

const getTabelData = () => {
  const { curPage, pageSize } = toRefs(pageData)
  const params = {
    curPage: curPage.value,
    pageSize: pageSize.value
  } as any;
  const trimData = trimStringParams(queryData)
  Object.keys(trimData).forEach(key => {
    const kVal = trimData[key as keyof typeof trimData]
    if (kVal) {
      params[key] = kVal
    }
  })
  tableLoading[0] = 1
  getGroupOrgCertTreeApi(params)
    .then((res) => {
      const { data, pageInfo } = res;
      tableData.value = data;
      total.value = pageInfo?.totalRows
      defaultExpandAll.value = params.name && params.name.length > 0
    })
    .finally(() => {
      tableLoading[0] = 0;
    });
};
const getCertifiData = () => {
  const params = {
    curPage: 1,
    pageSize: 10000
  } as any
  tableLoading[1] = 1
  getCertifiedListApi(params).then(res => {
    let { data } = res;
    certListData.value = data
  }).finally(() => {
    tableLoading[1] = 0
  })
};


const handleSizeChange = (val: number) => {
  pageData.pageSize = val
  pageData.curPage = 1
  getTabelData()
}
const handleCurrentChange = (val: number) => {
  pageData.curPage = val
  getTabelData()
}
const resetQuery = () => {
  Object.assign(queryData, defaultQueryData)
  getTabelData()
}

const addOrg = (type: string, data?: any) => {
  editOrgDialogRef.value?.inint(type, data ?? null)
}

const batchAddOrg = () => {
  batchUploadOrgDialogRef.value?.inint()
}

const setStatus = (data: any) => {
  if (data.status === 'enable') {
    const message = $t('orgMgr.orgStatusTipTxt')
    confirmSubmit(message).then(() => {
      tableLoading[0] = 1
      updateGroupOrgStatusApi({ id: data.id, status: 'disable' }).then(() => {
        getTabelData()
      }).finally(() => {
        tableLoading[0] = 0
      })
    }).catch(() => {
    })
  } else {
    tableLoading[0] = 1
    updateGroupOrgStatusApi({ id: data.id, status: 'enable' }).then(() => {
        getTabelData()
      }).finally(() => {
        tableLoading[0] = 0
      })
  }
}
 
const editOrg = (data: any) => {
  const editData = {
    ...data
  }
  editOrgDialogRef.value?.inint('EDIT', editData)
}
const deleteOrg = (data: any) => {
  ElMessageBox.confirm(
    $t('common.submitTxt', [$t('common.deleteTxt', [$t('orgMgr.orgTxt')])]),
    $t('common.tipTxt'),
    {
      confirmButtonText: $t('common.submitTxt'),
      cancelButtonText: $t('common.cancelTxt'),
      type: 'warning',
    }
  )
    .then(() => {
      tableLoading[0] = 1
      deleteOrgApi(data.id).then(() => {
        getTabelData()
      }).finally(() => {
        tableLoading[0] = 0
      })
    })
    .catch(() => { })
}
const getCertName = (id: any) => {
  const name = certListData.value.find((item: { name: any, id: any }) => item.id === id)?.name ?? '--'
  return name
}
watch(
  () => tableLoading,
  (val) => {
    if (val) {
      const isLoading = val.some(i => i === 1)
      loading.value = isLoading
    }
  },
  { deep: true },
)

onMounted(() => {
  getTabelData();
  getCertifiData();
})

</script>
<template>
  <Page class="h-full">
    <section class="flex h-full flex-col bg-[#fff] p-[24px] rounded-sm">
      <Query v-model="queryData" class="mb-[5px]" :certListData="certListData" @query-data="getTabelData"
        @reset-query="resetQuery" />
      <div class="mb-[16px]">
        <el-button type="primary" @click="addOrg('PLEVEL')">
          {{ $t('common.newTxt') }}
        </el-button>
        <!-- <el-button @click="batchAddOrg">
          {{ $t('common.batchNewTxt') }}
        </el-button> -->
      </div>
      <el-table :default-expand-all="defaultExpandAll" row-key="id" :data="tableData" v-loading="loading" height="100%">
        <el-table-column prop="name" :label="$t('orgMgr.orgGroupNameTxt')" min-width="200">
          <template #default="{ row }">
            <span>{{ row.name ?? '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="certifiedId" :label="$t('orgMgr.bindCertTxt')" min-width="200">
          <template #default="{ row }">
            <span>{{ getCertName(row.certifiedId) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" :label="$t('orgMgr.orgGroupStatusTxt')" min-width="80">
          <template #default="{ row }">
            <div class="flex items-center">
              <span class="block rounded-[50%] w-[10px] h-[10px]"
                :style="{background: row.status == 'enable' ? '#30A46C' : '#AEAEAE' }"></span>
              <span class="text-[12px] text-[#557283] ml-[4px]">{{ row.status === 'enable' ? $t('common.activeTxt') : $t('common.inactiveTxt') }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" :label="$t('common.createTimeTxt')" min-width="100">
          <template #default="{ row }">
            <div>{{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}</div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" :label="$t('common.handleTxt')" min-width="80">
          <template #default="{ row }">
            <el-tooltip effect="dark" :content="$t('common.newTxt', [$t('orgMgr.subOrgTxt')]) " :show-after="1000" placement="top">
                <el-button link @click="addOrg('SUBLEVEL', row)">
                  <el-icon :style="{ backgroundImage: `url(${subOrgIcon})`, backgroundSize: '100% 100%', backgroundRepeat: 'no-repeat', backgroundPosition: 'center' }"></el-icon>
                </el-button>
              </el-tooltip>
            <el-tooltip effect="dark" :content="row.status === 'enable' ? $t('common.inactiveTxt') : $t('common.activeTxt')"
              :show-after="1000" placement="top">
              <el-button :icon="row.status === 'enable' ? Ban : SquarePlay" link @click="setStatus(row)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" :content="$t('common.editTxt')" :show-after="1000" placement="top">
              <el-button :icon="Pencil" link @click="editOrg(row)"></el-button>
            </el-tooltip>
            <!-- <el-tooltip effect="dark" :content="$t('common.deleteTxt')" :show-after="1000" placement="top">
              <el-button :icon="Trash2" :disabled="row.status === 'enable'" link @click="deleteOrg(row)"></el-button>
            </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>
      <ElPagination @size-change="handleSizeChange" @current-change="handleCurrentChange" class="pagination pt-[15px]"
        size="small" layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 50, 100]"
        :page-size="pageData.pageSize" :total="total"></ElPagination>
    </section>
    <EditOrgDialog ref="editOrgDialogRef" @queryTable="getTabelData" :certListData="certListData"></EditOrgDialog>
    <BatchUploadOrgDialog ref="batchUploadOrgDialogRef" @queryTable="getTabelData"></BatchUploadOrgDialog>
  </Page>
</template>
